package com.lv.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lv.common.BaseContext;
import com.lv.common.R;
import com.lv.dto.OrderDto;
import com.lv.pojo.OrderDetail;
import com.lv.pojo.Orders;
import com.lv.pojo.ShoppingCart;
import com.lv.service.OrderDetailService;
import com.lv.service.OrdersService;
import com.lv.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:晓风残月Lx
 * @Date: 2022/5/11 15:19
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submint(@RequestBody Orders orders){
        log.info("订单数据:{}",orders);

        ordersService.submit(orders);

        return R.success("下单成功");
    }

    /**
     * 后台查询订单明细
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param ednTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize,String number,String beginTime,String ednTime){
        // 分页构造器
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        // 构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();

        // 添加查询条件
        queryWrapper.like(number!=null,Orders::getNumber,number)
                .gt(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime)
                .lt(StringUtils.isNotEmpty(ednTime),Orders::getOrderTime,ednTime);

        ordersService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 用户订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(Integer page,Integer pageSize){

        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrderDto> orderDtoPage=new Page<>(page,pageSize);
        //构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,orderDtoPage,"recodes");

        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();

        List<Orders> records = pageInfo.getRecords();
        List<OrderDto> orderDtoList=records.stream().map((item)->{
            OrderDto orderDto = new OrderDto();

            Long orderId = item.getId();
            List<OrderDetail> orderDetailList = orderDetailService.getOrderDetailListByOrderId(orderId);
            BeanUtils.copyProperties(item,orderDto);

            orderDto.setOrderDetails(orderDetailList);
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(orderDtoList);
        return R.success(pageInfo);

    }


    @PostMapping("/again")
    public R<String> again(@RequestBody Map<String,String> map){

        Long id = Long.parseLong(map.get("id"));

        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);

        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        shoppingCartService.clean();

        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts=orderDetailList.stream().map((item)->{

            ShoppingCart shoppingCart=new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId!=null){
                shoppingCart.setDishId(dishId);
            }else{
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;

        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCarts);

        return R.success("操作成功");

    }

    /**
     * 订单管理状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> status(@RequestBody Orders orders){

        Orders ordersById = ordersService.getById(orders.getId());

        ordersById.setStatus(orders.getStatus());

        ordersService.updateById(ordersById);

        return R.success("操作成功");
    }


}
